package edu.uwosh.cs342.placestobe;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import edu.uwosh.cs342.placestobe.R;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends MapActivity implements LocationListener {
	/** Called when the activity is first created. */

	MapController mControl;
	GeoPoint geoP;
	MapView mapView;
	LocationManager locationManager;
	List<Overlay> mapOverlays;
	public static String[] placesA;
	public static int size;
	public static Double[] latA;
	public static Double[] lngA;
	String[] friendsNameList;
	double[] friendsLat;
	double[] friendsLongi;
	ArrayList<CustomLocation> locationList;
	boolean overlayFilled = false;
	// CustomLocation[] locationList;

	static String userID = "";

	// double lat = 44.028513;
	// double longi = -88.551293;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Toast.makeText(getApplicationContext(), "Welcome " + userID,
				Toast.LENGTH_LONG).show();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public void instantiateLocations() {
		// Add locations here
		locationList = new ArrayList<CustomLocation>();
		// CustomLocation takes a String, double, double
		// CustomLocation x = new CustomLocation("Culvers", 44.003335
		// ,-88.581352);
		// CustomLocation y = new CustomLocation("Toppers", 44.021260,
		// -88.547230);
		// locationList.add(x);
		// locationList.add(y);
	}

	public void onLocationChanged(Location location) {
		if(mapOverlays != null){
			mapOverlays.clear();
		}
		
		// When DDMS sends latitude and longitude this method is called to
		// reset the user's position on the map
		if (location != null) {
			// get the latitude and longitude
			Double latitude = location.getLatitude();
			Double longitude = location.getLongitude();

//			// display the user's location as a toast
//			Toast.makeText(getApplicationContext(), latitude + "," + longitude,
//					Toast.LENGTH_LONG).show();

			geoP = new GeoPoint((int) (latitude * 1E6), (int) (longitude * 1E6));
			mapView = (MapView) findViewById(R.id.mapView);

			// configure zoom depth and centered area
			MapController mc = mapView.getController();
			mc.setCenter(geoP);
			mc.setZoom(15);

			// Show user's location with a red pin/pole
			mapOverlays = mapView.getOverlays();
			Drawable drawable = this.getResources().getDrawable(
					R.drawable.user_pin);
			ResourcesOverlay itemizedoverlay = new ResourcesOverlay(drawable);

			// SET USER NAME HERE
			OverlayItem overlayitem = new OverlayItem(geoP, userID, "");

			itemizedoverlay.addOverlay(overlayitem);
			mapOverlays.add(itemizedoverlay);
			String res ="";
			try {  
				res= CustomHttpClient.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/updateLoc.php?user="+userID+"&lat="+latitude+"&long="+longitude); 
				res=res.toString().trim();    
			} catch (Exception e) {  }
			String type = "restaurant"; // set whatever type of search you would
										// like
			String[] results = GoogleJSON.test(latitude, longitude, type);
			// System.out.println(results.length); //for testing
			String places[] = new String[(results.length - 1)];
			String spoints[] = new String[(results.length - 1)];
			for (int i = 0; i < results.length - 1; i++) {
				if (results[i].toString() != null) {
					// System.out.println(results[i].toString() + "  " + i);
					// //testing
					StringTokenizer st = new StringTokenizer(results[i], ":");
					places[i] = ((String) st.nextElement()).replace("[", ""); // formatting
					places[i] = places[i].replace(",", ""); // formatting
					spoints[i] = (String) st.nextElement();

				}
			}

			Double lat[] = new Double[results.length - 1];
			Double lng[] = new Double[results.length - 1];
			for (int i = 0; i < places.length; i++) {
				StringTokenizer st1 = new StringTokenizer(spoints[i], " ");
				lat[i] = Double.parseDouble((String) st1.nextElement());
				lng[i] = Double.parseDouble((String) st1.nextElement());
				// System.out.println("Lat: "+lat[i]+" LONG: "+lng[i]);
			}

			// System.out.println("PRRRRIIIIINNNNNTTTTT");
			for (int i = 0; i < places.length; i++) {
				// System.out.println("place: "+places[i]+" points: "+spoints[i]);
				List<Overlay> mapOverlays1 = mapView.getOverlays();
				Drawable drawable1 = this.getResources().getDrawable(
						R.drawable.friend_pin);
				LocationOverlay itemizedoverlay1 = new LocationOverlay(drawable1, this, friendsNameList);
//				ResourcesOverlay itemizedoverlay1 = new ResourcesOverlay(
//						drawable1);

				geoP = new GeoPoint((int) (lat[i] * 1E6), (int) (lng[i] * 1E6));
				// SET USER NAME HERE
				OverlayItem overlayitem1 = new OverlayItem(geoP, places[i], "");
				itemizedoverlay1.addOverlay(overlayitem1);
				mapOverlays1.add(itemizedoverlay1);
			}
			placesA = places;
			latA = lat;
			lngA = lng;
			size = places.length;
			
		}
		
	}

	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater blowUp = getMenuInflater();
		blowUp.inflate(R.menu.menuoptions, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_requests:
//			showMeetingRequests();
			Intent invites = new Intent("android.intent.action.INVITESACTIVITY");
			invites.putExtra("username", userID);
			startActivity(invites);
			break;
		case R.id.menu_meetings:
			Intent meetingList = new Intent("android.intent.action.MEETINGLIST");
			meetingList.putExtra("username", userID);
			startActivity(meetingList);
			break;
		case R.id.menu_friends:
			Intent friendsIntent = new Intent("android.intent.action.FRIENDSACTIVITY");
			startActivity(friendsIntent);
			break;
		case R.id.menu_make:
			if(geoP!=null){
				Intent makeIntent = new Intent("android.intent.action.MAKEMEETING");
				makeIntent.putExtra("listOfFriends", friendsNameList);
				makeIntent.putExtra("locationName", "");
				startActivity(makeIntent);
			}else{
				Toast.makeText(getApplicationContext(),"Must send geolocation before creating meeting", Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.menu_refresh:
			Intent myIntent = new Intent("android.intent.action.MAP");
			startActivity(myIntent);
			break;
		}

		return false;
	}

	@Override
	public void onResume() {
		super.onResume();

		// used to be in onCreate
		mapView = (MapView) findViewById(R.id.mapView);
		mapView.displayZoomControls(true);
		mapView.setBuiltInZoomControls(true);

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE); // fine location data
		criteria.setBearingRequired(true); // need bearing to rotate map
		criteria.setCostAllowed(true); // OK to incur monetary cost
		criteria.setPowerRequirement(Criteria.POWER_LOW); // try to conserve
		criteria.setAltitudeRequired(false); // don't need altitude data

		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		String provider = locationManager.getBestProvider(criteria, true);

		locationManager.requestLocationUpdates(provider, 500, 500, this);

		new AsyncGetFriendsInfo().execute((Object[]) null);

		// end used to be in onCreate
	}

	private void displayFriends() {
		if (overlayFilled) {
			List<Overlay> mapOverlays = mapView.getOverlays();

			// Put friends on the map
			Drawable friendDrawable = this.getResources().getDrawable(
					R.drawable.friend_green_pin);
			ResourcesOverlay itemizedFriendOverlay = new ResourcesOverlay(
					friendDrawable);

			for (int i = 0; i < friendsLat.length; i++) {
				GeoPoint friendPoint = new GeoPoint(
						(int) (friendsLat[i] * 1E6),
						(int) (friendsLongi[i] * 1E6));
				OverlayItem friendOverlay = new OverlayItem(friendPoint,
						friendsNameList[i], "friend");
				itemizedFriendOverlay.addOverlay(friendOverlay);
			}
			mapOverlays.add(itemizedFriendOverlay);

			instantiateLocations();

			LocationOverlay locationItemizedOverlay = new LocationOverlay(
					friendDrawable, this, friendsNameList);
			for (int i = 0; i < locationList.size(); i++) {
				double x = locationList.get(i).getLatitude();
				double y = locationList.get(i).getLongitude();
				GeoPoint geoX = new GeoPoint((int) (x * 1E6), (int) (y * 1E6));
				OverlayItem locOverlay = new OverlayItem(geoX, locationList
						.get(i).getName(), "");
				locationItemizedOverlay.addOverlay(locOverlay);
				mapOverlays.add(locationItemizedOverlay);
			}
		}

		
	}

	public void showMeetingRequests() {
		// dummy friend list ----- take out later
		String[] dummyList = new String[] { "Bobby", "Sally" };

		// ********* web service: get all requests from friends ********
		final String[] requestList = dummyList;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Meeting Requests");
		builder.setItems(requestList, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				String friendChosen = requestList[which];
				meetingRequestDialog(friendChosen);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public void meetingRequestDialog(String friendRequesting) {
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		dialogBuilder.setTitle("Meeting Request!");
		dialogBuilder.setMessage("Would you like to meet with "
				+ friendRequesting);

		// Yes to request
		dialogBuilder.setPositiveButton("Yes",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// ********** web service to accept the meeting request
						// ********

					}
				});

		// No to request
		dialogBuilder.setNegativeButton("No",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// ********** web service to decline the meeting request
						// ********

					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub

	}

	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	protected static void setUserID(String id) {
		userID = id;
	}

	private class AsyncGetFriendsInfo extends AsyncTask<Object, Object, Object> {
		String response = "";

		@Override
		protected Object doInBackground(Object... arg0) {
			try {
				response = CustomHttpClient
						.executeHttpGet("http://cs346.cs.uwosh.edu/students/blairm83/cs342group6/viewUsers.php?userID="+ userID);
				response = response.toString().trim();
			} catch (Exception e) {
				System.out.println(e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			// fillFriends(response);
			try {
				if (response != null) {
					StringTokenizer tk = new StringTokenizer(response);
					int strSizes = tk.countTokens() / 3;
					friendsNameList = new String[strSizes];
					friendsLat = new double[strSizes];
					friendsLongi = new double[strSizes];

					for (int i = 0; tk.hasMoreTokens(); i++) {
						friendsNameList[i] = tk.nextToken();
						String lat = tk.nextToken();
						String longi = tk.nextToken();
						if (lat.equalsIgnoreCase("null")) {
							friendsLat[i] = 0;
							friendsLongi[i] = 0;
						} else {
							friendsLat[i] = Double.parseDouble(lat);
							friendsLongi[i] = Double.parseDouble(longi);
						}
					}
					
				}
				overlayFilled = true;
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(getApplicationContext(),
						"Error retrieving friends data from server.",
						Toast.LENGTH_LONG).show();
			}
			displayFriends();

		}

	}

}
